package com.lzh.msmservice.controller;

import com.lzh.commonutils.R;
import com.lzh.msmservice.service.MsmService;
import com.lzh.msmservice.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Classname MsmController
 * @Description TODO
 * @Date 2021/3/5 15:20
 * @Author Anonymous
 */
@RestController
@RequestMapping("/edumsm/msm")
@CrossOrigin
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //发送短信的方法
    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone) {
        //从redis中获取验证码，如果获取到直接返回
        String code = redisTemplate.opsForValue().get(phone);
        //，如果redis获取不到，生成随机值，传递给阿里云进行发送
        code = RandomUtil.getFourBitRandom();
        Map<String,Object> param = new HashMap<>();
        param.put("code", code);
        boolean isSend = msmService.send(param,phone);
        if (isSend) {
            //设置验证码的有效时间，参数分别为手机号，验证码，时间，单位，也就是5分钟内有效
            redisTemplate.opsForValue().set(phone, code,5, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error().message("发送短信失败");
        }

    }

}
